import cloudbase from "@cloudbase/js-sdk";
import cloudConfig from 'configs/cloudset'
import * as lib from "./lib";

if (!cloudConfig.envid) {
  console.warn('必须填写云端的环境ID，请参考。。。')
}

const app = cloudbase.init({ env: cloudConfig.envid });
const auth = app.auth();
const db = app.database();

function callCloud(url, param={}, ctx) {
  if (lib.isString(url)) {
    let ary = url.split('/')
    if (!ary[0]) {
      ary.shift()
    }
    if (ary.length) {
      let api = ary[0]
      let coll = ary[1]
      let action = ary[2]
      let dataKey = ary[3]

      param.__collection__ = coll
      param.__action__ = action
      param.__datakey__ = dataKey
      // param.__createtime__ = dataKey
      if (typeof wx === 'undefined') {
        param.__web_uid__ = 'administrator'
      }
      return new Promise((resolve, rej)=>{
        let application = null
        if (typeof wx === 'undefined') {
          application = app
        } else {
          application = wx.cloud
        }
        application.callFunction({
          name: api,
          data: param,
        })
        .then((res) => {
          resolve(res)
        })
        .catch(console.error);
      })
    }
  }
}

export {
  app,
  auth,
  cloudbase,
  db,
  cloudConfig,
  lib,
  callCloud
}